package servers

import (
	"fmt"
	"log"
	"net"
	"smart/methods"
	"smart/models"
)

const port string = "8991"

// 定义服务器结构
type Server struct {
	listener    *net.TCPListener
	conns       map[string]net.Conn
	messageRecv chan *models.Msg
}

func (s *Server) InitServer() error {
	s.messageRecv = make(chan *models.Msg, 1000)
	s.conns = make(map[string]net.Conn)
	host := ":" + port
	tcpAddr, err := net.ResolveTCPAddr("tcp", host)
	if err != nil {
		log.Println("生成TCP地址错误!")
		return err
	}
	listener, err := net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		log.Println("创建TCP服务错误！")
		return err
	}
	s.listener = listener
	go s.broadcaseMessage()
	for {
		fmt.Printf("服务器启动localhost:%s\n", port)
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("客户端连接失败：", err.Error())
			continue
		}
		fmt.Println("用户连接成功", conn.RemoteAddr().String())
		go s.handleMessage(conn)
	}
}
func (s *Server) handleMessage(conn net.Conn) {
	for {
		message := make([]byte, 100)
		count, err := conn.Read(message)
		clearMsg := message[:count]
		if err != nil {
			log.Println(err.Error())
			s.closeConnection(conn)
			break
		}
		status := disposeMessage(string(clearMsg))
		// 构建操作结构体
		fmt.Printf("%d", status)
		switch status {
		case 0:
			msg := &models.Msg{}
			msg.Method = string(message[0:20])
			msg.Command = string(message[20:40])
			msg.Name = string(message[40:80])
			msg.RecvMethod = string(message[80:])
			msg.Conn = conn
			s.messageRecv <- msg
		case 1:
			s.closeConnection(conn)
		case 2:
			conn.Write([]byte("PONG\n"))
		}
	}
	s.closeConnection(conn)

}

func (s *Server) broadcaseMessage() {
	for {
		select {
		case msg := <-s.messageRecv:
			methods.TransMethod(msg)
		}
	}

}

func (s *Server) closeConnection(conn net.Conn) {
	delete(s.conns, conn.RemoteAddr().String())
	conn.Close()
	log.Println(s.conns)
}

func disposeMessage(target string) int {
	if target == "PING" {
		return 2
	} else if target == "exit" {
		return 1
	}
	return 0
}
